package com.example.androidtest.handler;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class LoadImageRunnable implements Runnable {
    private int myThreadId;
    private Handler mHandler;
    private String sUrl;

    /**
     * @param myThreadId
     * @param mHandler
     * @param sUrl
     */
    public LoadImageRunnable(int myThreadId, Handler mHandler, String sUrl) {
        this.myThreadId = myThreadId;
        this.mHandler = mHandler;
        this.sUrl = sUrl;
    }

    @Override
    public void run() {
        Message message = new Message();
        message.what = myThreadId;
        message.obj = LoadImageFromNetwork();
        mHandler.sendMessage(message);
        System.out.println("LoadImageRunnable----" + Thread.currentThread().getName());
    }

    /**
     * @return bitmap
     * 从外部链接加载图片
     */
    private Bitmap LoadImageFromNetwork() {
        Bitmap bitmap = null;
        try {
            URL url = new URL(sUrl);
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(10 + myThreadId);
        } catch (IOException e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(10 + myThreadId);
        }
        return bitmap;
    }
}
